<?php

namespace App\Http\Controllers\Wechat;

use App\Models\NewBookRecommend;
use App\Models\NewBookRecommendCollect;
use App\Models\NewBookRecommendType;
use App\Validate\NewBookRecommendValidate;

/**
 * 新书推荐（独立功能）
 */
class NewBookRecommendController extends CommonController
{
    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new NewBookRecommend();
        $this->validate = new NewBookRecommendValidate();
    }

    /**
     * 新书推荐类型
     */
    public function typeList()
    {
        $typeModel = new NewBookRecommendType();
        $condition[] = ['is_del', '=', 1];

        return $typeModel->getFilterList(['id', 'type_name'], $condition);
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词
     * @param keywords_type string 搜索关键词类型 0或空表示全部  1 书名 2 作者名 3 ISBN号
     * @param type_id int 书籍类型(不传查询所有)
     * @param is_recom int 是否推荐 1是 2否
     * @param token int token可选
     */
    public function lists()
    {
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $keywords_type = $this->request->keywords_type;
        $type_id = $this->request->type_id;
        $user_id = $this->request->user_info['id'];

        $res = $this->model->lists($type_id, $keywords, $keywords_type, 1, $limit);

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(16);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            //判断是否收藏
            if (!empty($user_id)) {
                $isCollect = NewBookRecommendCollect::isCollect($val['id'], $user_id, 1);
                $res['data'][$key]['is_collect'] = empty($isCollect) ? false : true; //是否收藏
            } else {
                $res['data'][$key]['is_collect'] = false; //是否收藏
            }
            $res['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
        }


        $res = $this->disPageData($res);
        $res['data'] = $this->disDataSameLevel($res['data'], 'con_type', ['type_name' => 'type_name']);

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param book_id int 书籍id
     * @param token int token  可选
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];

        $res = $this->model->with('conType')->where('is_del', 1)->find($this->request->book_id);

        if (!$res) {
            return $this->returnApi(201, "参数传递错误", "YES");
        }
        $res = $res->toArray();
        $res = $this->disDataSameLevel($res, 'con_type', ['type_name' => 'type_name']);

        //判断是否收藏 和 是否加入购物车
        if (!empty($user_id)) {
            $isCollect = NewBookRecommendCollect::isCollect($this->request->book_id, $user_id);
            $res['is_collect'] = empty($isCollect) ? false : true; //是否收藏
        } else {
            $res['is_collect'] = false; //未收藏
        }

        $res['intro'] = str_replace('&nbsp;', '', strip_tags($res['intro']));

        unset($res['is_del']);
        unset($res['con_type']);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 新书收藏与取消收藏
     * @param  token ：用户 token
     * @param  book_id 书籍id
     */
    public function newBookRecommendCollect()
    {
        // 自动验证
        if (!$this->validate->scene('new_book_recommend_collect')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $book_id = $this->request->book_id;
        $user_id = $this->request->user_info['id'];

        $res = NewBookRecommendCollect::isCollect($book_id, $user_id);
        if (empty($res)) {
            $newBookRecommendCollectModel = new NewBookRecommendCollect();
            $result = $newBookRecommendCollectModel->add([
                'user_id' => $user_id,
                'book_id' => $book_id
            ]);
            $msg = '收藏';
        } else {
            $result = $res->delete();
            $msg = '取消收藏';
        }
        if ($result) {
            return $this->returnApi(200, $msg . '成功', true);
        }
        return $this->returnApi(202, $msg . '失败');
    }

    /**
     * 我的新书（推荐书）收藏列表
     * @param token ：用户 token
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function myNewBookRecommendCollectList()
    {
        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        $res = NewBookRecommendCollect::select('id', 'book_id', 'create_time')
            ->with(['newBookRecommendCollect' => function ($query) {
                $query->select('id', 'book_name', 'author', 'press', 'pre_time', 'isbn', 'price', 'img', 'intro');
            }])
            ->whereHas('newBookRecommendCollect', function ($query) {
                $query->where('is_del', 1);
            })
            ->where('user_id', $user_id)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        foreach ($res['data'] as &$val) {
            $val['book_name'] = $val['new_book_recommend_collect']['book_name'];
            $val['author'] = $val['new_book_recommend_collect']['author'];
            $val['press'] = $val['new_book_recommend_collect']['press'];
            $val['pre_time'] = $val['new_book_recommend_collect']['pre_time'];
            $val['isbn'] = $val['new_book_recommend_collect']['isbn'];
            $val['price'] = $val['new_book_recommend_collect']['price'];
            $val['img'] = $val['new_book_recommend_collect']['img'];
            $val['intro'] = str_replace('&nbsp;', '', strip_tags($val['new_book_recommend_collect']['intro']));

            unset($val['id']);
            unset($val['new_book_recommend_collect']);
        }

        if (!empty($res['data'])) {
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res['data']);
        }
        return $this->returnApi(203, '暂无数据');
    }
}
